package by.epam.xslttask.controller;

import by.epam.xslttask.command.Command;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Darya_Hrishanovich
 * Date: 7/6/12
 * Time: 2:20 AM
 * To change this template use File | Settings | File Templates.
 */
public class Controller extends HttpServlet {
    private static final String SERVLET = "/servlet?";
    private static final String EQ = "=";
    private static final String AMP = "&";
    private static final String SLASH = "/";
    private ControllerHelper helper;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        helper = new ControllerHelper();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        process(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        process(request, response);
    }

    private void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String relPath = getServletContext().getRealPath(SLASH);
        Command command = helper.identifyCommand(request, response, relPath);
        Map<String, String> params;
        if((params = command.execute()) != null) {
            Iterator it = params.entrySet().iterator();
            StringBuilder path = new StringBuilder(SERVLET);
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                path.append(entry.getKey()).append(EQ).append(entry.getValue());
                if(it.hasNext()) {
                    path.append(AMP);
                }
            }
            response.sendRedirect(path.toString());
        }
    }
}
